package command

import (
	"errors"
	"zin/config"
	"zin/framework/cobra"
	"zin/framework/util"
	"github.com/spf13/cast"
	"log"
	"strings"
)

func initConfigCommand() *cobra.Command {
	return configCommand
}

var configCommand = &cobra.Command{
	Use:   "config",
	Short: "獲取配置項值 config xxx | xxx.host",
	RunE: func(cmd *cobra.Command, args []string) error {
		configMap := map[string]interface{}{}
		err := util.Struct2Map(config.Conf, &configMap)
		if err != nil {
			return err
		}
		if len(args) == 0 {
			return errors.New("爲攜帶任何參數")
		}
		argStr := args[0]

		argArr := strings.Split(argStr, ".")
		val := getConfig(configMap, argArr)
		log.Println(argStr, " = ", val)
		return nil
	},
}

func getConfig(source map[string]interface{}, path []string) interface{} {
	if len(path) == 0 {
		return source
	}
	if next, ok := source[path[0]]; ok {
		if len(path) == 1 {
			return next
		}
		switch next.(type) {
		case map[interface{}]interface{}:
			return getConfig(cast.ToStringMap(next), path[1:])
		case map[string]interface{}:
			return getConfig(next.(map[string]interface{}), path[1:])
		default:
			return nil
		}
	}
	return nil
}
